// pages/mbook/mbook.js
const app = getApp();
var funcs = require('../../static/js/funcs.js');
import {
  cities,
  areas
} from '../../static/js/city';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    select_date: '2024-11',
    customer_list:[],
    period_list: [],
    week: ["一","二","三","四","五","六","日"],
    select_period:null,
    cities,
    areas,
    city: "",
    area: "",
    city_area:"请选择机构位置",
    select_inst:"请选择网点",
    multiIndex: [0, 0],
    objectMultiArray: [cities, areas[0]],
    networkList: [],
    inst_list:[],
    mapid_list:[],
    selectedmapid: ""
  },
  /**
   * 选择预约时段
   * @param {*} e 
   */
  select_period: function (e) {
    let that = this
    console.log(e.currentTarget.dataset)
    let selectedDay = e.currentTarget.dataset.selectedday
    let isafter = e.currentTarget.dataset.isafter; //是否限制
    let display = e.currentTarget.dataset.display;
    if (display==0) {
      console.log("日期无法选择，不予展示")
      return;
    }
    if (isafter==0) {
      console.log("日期无法选择，已过时")
      return;
    }
    console.log(selectedDay)
    this.setData({
      select_period: selectedDay,
    })
    console.log(this.data.select_period)
    funcs.getBooksByInst(this.data.selectedmapid,Number(this.data.selected_year),Number(this.data.selected_month),Number(this.data.select_period)).then(res=>{
      if(res.data.succeed){
        console.log(res.data.data.bookinfos)
        that.setData({
          customer_list:res.data.data.bookinfos
        })
      }
    })
  },
  select_date_func: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    let result = e.detail.value.split('-');
    console.log(result)
    let year = Number(result[0]);
    let month = Number(result[1]);
    this.setData({
      select_date:e.detail.value,
      selected_year: year,
      selected_month: month
    })

    let _this = this;
    funcs.getAllDays4Month2(year,month).then(res => {
      let result = res.data.data;
      console.log(result)
      _this.setData({
        period_list: result,
        customer_list: [],
        select_period: null
      })
    })
  },  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let openid = app.globalData.openid
    if(app.globalData.loginedFlag==false){
      this.setData({
        loginedFlag: false
      })
      wx.reLaunch({
        url: '/pages/my/my',
      })
      wx.showToast({
        title: "请先绑定",
        icon: 'none',
        duration: 2000
      })
      return
    }
    let that = this
    funcs.judgeStaff(openid).then(res=>{
      if(res.data.succeed){
        console.log("该员工已注册")
        console.log(res.data.data)
        app.globalData.loginedFlag = true
        this.setData({
          loginedFlag: true,
          area:res.data.data.area,
          city:res.data.data.city,
          selectedmapid:res.data.data.mapId,
          select_inst:res.data.data.inst==""? "请选择":res.data.data.inst,
          // city:res.data.data.city,
          // area:res.data.data.area,
          // city_area: res.data.data.city+"-"+res.data.data.area
        })
        if(res.data.data.city!=null&&res.data.data.area!=null&&res.data.data.city.length>0&&res.data.data.area.length>0){
          this.fresh(res.data.data.city,res.data.data.area)
          if(res.data.data.mapId!=null&&res.data.data.mapId.length>0){
            if(res.data.data.mapId.includes("_")){
              let newmapId = this.truncateToChar(res.data.data.mapId,"_")
              console.log("截取后：",newmapId)
              funcs.getInstByMapId(newmapId).then(res=>{
                if(res.data.succeed){
                  that.setData({
                    selectedmapid:newmapId,
                    select_inst:res.data.data.name
                  })
                }
                this.freshbooks()
              })
            }else{
              this.freshbooks()
            }
          }
        }
      }else{
        app.globalData.loginedFlag = false
        this.setData({
          loginedFlag: false
        })
        wx.reLaunch({
          url: '/pages/my/my',
        })
        wx.showToast({
          title: "请先绑定",
          icon: 'none',
          duration: 2000
        })
      }
    })
    let _this = this
    const now = new Date();
    // 获取当前年份
    const year = now.getFullYear();
    // 获取当前月份（需要加1，因为getMonth返回的月份是从0开始计数的）
    const month = now.getMonth() + 1;
    const day = now.getDate();
    this.setData({
      select_period:day,
      selected_year: year,
      selected_month: month
    })
    console.log(year+"-"+month+"-"+day)
    funcs.getAllDays4Month2(year,month).then(res => {
      let result = res.data.data;
      console.log(result)
      _this.setData({
        period_list: result,
        select_date: year+"-"+month
      })
    })
  },

  truncateToChar(str, charToFind) {
    const index = str.indexOf(charToFind);
    if (index >= 0) {
        return str.substring(0, index);
    }
    return str; // 如果字符未找到，返回原字符串
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let openid = app.globalData.openid
    if(app.globalData.loginedFlag==false){
      this.setData({
        loginedFlag: false
      })
      wx.reLaunch({
        url: '/pages/my/my',
      })
      wx.showToast({
        title: "请先绑定",
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.freshbooks()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  processbook(e){
    let that = this
    let openid = app.globalData.openid
    let data = e.currentTarget.dataset
    funcs.processBook(data.bookid,openid).then(res=>{
      if(res.data.succeed){
        console.log("处理成功")
        wx.showToast({
          title: "处理成功",
          icon: 'success',
          duration: 2000
        })
        funcs.getBooksByInst(this.data.selectedmapid,Number(this.data.selected_year),Number(this.data.selected_month),Number(this.data.select_period)).then(res=>{
          console.log(res.data.data.bookinfos)
          if(res.data.succeed){
            that.setData({
              customer_list:res.data.data.bookinfos
            })
          }
        })
      }
    })


    // console.log(data.bookid)
    // console.log("开始处理预约")
  },

  bindColumnCityChange(event) {
    console.log('修改的列为', event.detail.column, '，值为', event.detail.value);
    switch (event.detail.column) {
      case 0: //修改第一列
        let arr = this.data.multiIndex;
        arr[0] = event.detail.value;
        arr[1] = 0;
        this.setData({
          objectMultiArray: [cities, areas[event.detail.value]],
          multiIndex: arr,
        })
        break;
      case 1: //修改第二列
        let arr2 = this.data.multiIndex;
        arr2[1] = event.detail.value;
        // console.log(arr2)
        this.setData({
          multiIndex: arr2,
        })
        break;
    }
    // console.log(this.data.multiIndex)
  },

   bindCityChange(event) {
    console.log('picker发送选择改变，携带值为', event.detail.value)
    let city_index = event.detail.value[0];
    let area_index = event.detail.value[1];
    let city = this.data.cities[city_index].name;
    let area = this.data.objectMultiArray[1][area_index].name;
    this.fresh(city,area)
  },

  fresh(city,area){
    funcs.getAllByAreaNameWithNot(city,area).then(res => {
      // console.log(res.data);
      let real_networkList = []
      let networkList = res.data.data;
      let mapidList = []
      let instList = []
      networkList.map((item, index) => {
        if (item.telephone != null && item.telephone.length > 0)
          real_networkList.push(item);
          instList.push(item.name)
          mapidList.push(item.map_id)
      })
      this.setData({
        networkList: real_networkList,
        inst_list: instList,
        mapid_list: mapidList
      })
    }).then(() => {
      this.setData({
        city: city,
        area: area,
        city_area: city + '-' + area
      })
      console.log(this.data.city)
      console.log(this.data.area)
    })
  },

  select_inst_func:function(e){
    console.log(this.data.networkList)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    this.setData({
      select_inst: this.data.inst_list[index],
      selectedmapid: this.data.mapid_list[index]
    })
    this.freshbooks()
  },
  freshbooks(){
    let that = this
    console.log("获取的预约mapid信息为：",this.data.selectedmapid)
    funcs.getBooksByInst(this.data.selectedmapid,Number(this.data.selected_year),Number(this.data.selected_month),Number(this.data.select_period)).then(res=>{
      console.log(res.data.data.bookinfos)
      if(res.data.succeed){
        that.setData({
          customer_list:res.data.data.bookinfos
        })
      }
    })
  },
})